import { Component, OnInit } from '@angular/core';
import { ScenarioService } from '../services/scenario.service';
import { firstValueFrom } from "rxjs";
import { ConfirmationService, MessageService } from 'primeng/api';
import { ScenarioConfig } from '../models';

@Component({
  selector: 'app-scenario-list',
  templateUrl: './scenario-list.component.html',
  styleUrl: './scenario-list.component.scss'
})
export class ScenarioListComponent implements OnInit {
  items: ScenarioConfig[] = [];
  currentItem?: ScenarioConfig;
  isLoading: boolean = false;

  constructor(private service: ScenarioService,
    private messageService: MessageService,
    private confirmService: ConfirmationService) {

  }

  ngOnInit(): void {
    this._refreshList();
  }

  private _refreshList() {
    this.isLoading = true;
    return firstValueFrom(this.service.getList()).then(items => {
      this.items = items;
    }).finally(() => {
      this.isLoading = false;
    });
  }

  onSelectItem(item: ScenarioConfig) {
    this.currentItem = item;
  }

  onDeleteClick(id: string) {
    this.confirmService.confirm({
      message: '确定删除该记录?',
      header: '删除确认',
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: "p-button-danger",
      rejectButtonStyleClass: "p-button-secondary",
      acceptLabel: "确定",
      rejectLabel: "取消",
      accept: () => {
        this.service.delete(id).subscribe(res => {
          if (res) {
            this.messageService.add({ severity: 'success', summary: 'Success', detail: `成功删除记录: ${id}` });
          }
          this._refreshList();
        });
      },
      reject: () => {
      }
    });
  }


  onRefreshClick() {
    this._refreshList();
  }
}
